package com.xiaoai.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author
 * @Date 2021-09-20 20:00
 */
public class SaleTicketDemo02 {

    public static void main(String[] args){
        Ticket2 ticke2 = new Ticket2();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticke2.sale();
            }
        },"a").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticke2.sale();
            }
        },"b").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticke2.sale();
            }
        },"c").start();

    }

}

class Ticket2{
    private int number = 30;

    Lock lock = new ReentrantLock();

    public void sale(){
        // 加锁
        lock.lock();
        try {
            if (number > 0){
                System.out.println(Thread.currentThread().getName()+"卖出[ "+number--+" ]张票，剩余:["+number+"]");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 解锁
            lock.unlock();
        }
    }
}
